package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"news/models"
	"strconv"
	"time"
)

type NewController struct {
	beego.Controller
}

type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *NewController) Add() {
	title := c.GetString("title")
	timed := c.GetString("timed")
	typed := c.GetString("typed")

	news := models.News{
		Title: title,
		Timed: timed,
		Typed: typed,
	}

	err := models.DB.Create(&news).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}

func (c *NewController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	key := "list-" + strconv.Itoa(page)
	val, err := models.Rdb.Get(key).Result()
	jsonData := make(map[string]interface{})
	quick := models.DB.Model(&models.News{})

	if err != nil {
		var count int64
		err = quick.Count(&count).Error
		offset := (page - 1) * size
		var news []models.News
		err = quick.Limit(size).Offset(offset).Find(&news).Error
		if err != nil {
			c.Data["json"] = JsonR{
				Code: 0,
				Msg:  "展示失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		} else {
			jsonData["page"] = page
			jsonData["count"] = count
			jsonData["news"] = news

			res, _ := json.Marshal(&jsonData)
			value := string(res)
			models.Rdb.Set(key, value, time.Minute*5)

			c.Data["json"] = JsonR{
				Code: 200,
				Msg:  "展示成功-mysql",
				Data: jsonData,
			}
			c.ServeJSON()
		}
	} else {
		json.Unmarshal([]byte(val), &jsonData)
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "展示成功-redis",
			Data: jsonData,
		}
		c.ServeJSON()
	}
}

func (c *NewController) Update() {
	id, _ := c.GetInt("id")
	title := c.GetString("title")
	timed := c.GetString("timed")
	typed := c.GetString("typed")

	news := models.News{
		Id:    id,
		Title: title,
		Timed: timed,
		Typed: typed,
	}

	err := models.DB.Save(&news).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "修改成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}

func (c *NewController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.News{}, id).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
